package com.platform.qujia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.platform.qujia.controller.QuJiaPayV2Controller;
import com.platform.qujia.constantEnum.DecimalConstant;
import com.platform.qujia.dao.PayOrderHistoryMapper;
import com.platform.qujia.dao.PayOrderMapper;
import com.platform.qujia.dao.PosMachineMapper;
import com.platform.qujia.dao.ReductionActivityMapper;
import com.platform.qujia.enums.PayTypeEnum;
import com.platform.qujia.param.request.SxfQueryTerminalReq;
import com.platform.qujia.pay.strategy.SXFChannel;
import com.platform.qujia.pojo.PayOrder;
import com.platform.qujia.pojo.Station;
import com.platform.qujia.pojo.StationDeviceManager;
import com.platform.qujia.pojo.TradePaymentRecordsDO;
import com.platform.qujia.pojo.dto.SxfBankCardCallbackDTO;
import com.platform.qujia.pojo.dto.SxfQueryTerminalListDTO;
import com.platform.qujia.pojo.dto.SxfTerminalDTO;
import com.platform.qujia.service.ClassSettlementService;
import com.platform.qujia.pojo.dto.DivideAccountsSettingDto;
import com.platform.qujia.pojo.dto.TransactionDTO;
import com.platform.qujia.service.EnterpriseService;
import com.platform.qujia.service.SxfCallbackService;
import com.platform.qujia.service.TradePaymentRecordsService;
import com.platform.qujia.utils.JsonUtils;
import com.platform.qujia.utils.ApiRequestBean;
import com.platform.qujia.utils.HttpUtils;
import com.platform.qujia.utils.RSASignature;
import com.platform.qujia.utils.SXFPaySign;
import com.yunhua.oil.common.core.utils.SpringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @date 2023/11/9
 */
@Service
public class SxfCallbackServiceImpl implements SxfCallbackService {

    public static final String SUCCESS_RETURN_VALUE = "{\"code\":\"success\",\"msg\":\"成功\"}";
    public static final String FAIL_RETURN_VALUE = "{\"code\":\"fail\",\"msg\":\"失败\"}";

    private static final Logger log = LoggerFactory.getLogger(SxfCallbackServiceImpl.class);

    private String tianqueURLVal = "https://openapi.tianquetech.com";


    private String tradeReversePayPrivatekey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCjpAs/ZC8J+rL0vAFXvXmRCjga4pzLP5t/8TbmR3CeS3heYtw9ahE4gwkkqdwE9J7FoIUTkd9M/2v3k6aO4zQjtPj42zw6yX0XaJJpTF2MTagKZ8g1Sk9tLOE+tDjbfb6KFXe424ia6YcRC6gPdtfYMp508PH7+2HyYJneNjouJruQePibiQQ4gCrP6/hvyzQHDXO4h5kUbNIC0gcf0OgDqX2VpcRZv0mp/eu/2aC6O1qbJUkIJKPOzRMzapUEYAmuKN+XrGiTRkFBWF2LGWTesKWqeqV1IgbnMxXV6IvgZbVMTZ12OR1TuCcyf1MI84ONQ1/7JVUBGbJciEqRVlmXAgMBAAECggEAWXHbLAUoqP29P4Rb/4dzoVHCpP9k0Lut1VsVtP0rk3qRCpZi57bIPulw3/dwac0D0+YPl0jOk5mxfBvamJOb9kB/Lhc3brKfi2H/VUsGfyAbT8S2bFp326cCX3HG+kJbGcLuM77bhkFLMIf8jqdZB7VzY1woCKG5QfCHaiyd1Ic7Qj2dwiVFwNkFrZGcwCnvgZdlt2UyPoKWIyOEicU4XDCTwGLcBlRKmSQrvn95q0hV8+p8dwJxOrmXYi39JVjDQLkfk/+EfHvlHoxuMGwHvpaVPMHzzLfwssBG8ZMIiYcPOaIEU8UdXtwYarRa56YIEyuM5dQ0kaF4tsQtTt8/EQKBgQDXyFoeeeJ0raLGncFYFuZHSY/osDLhA8mWsxRZ3O9FtvXfmFiKGOfBIb5R0DgksJ3bnt3cPeH8HtHb9W//zDTJAaiKEp6CYlZqjfZfbiZvdNFkADN3RvwblByT6WinveufjDB0NJ7GUkjcsa0fJe6iHnyHrzLfL/JYXL6Q5BR4gwKBgQDCI9iWlb6S0I0pYGFoopkIKEfK34v6V94SJmE36Et1Jw/OhW/mMDPm05SuOijWRwggYQbGhkM5nAlvurBWDLDNF0Q69J3liJ78kt6iu4byMXhSAbL82cdu3xRv7h1l5VW0RJmjY/s1fSwP+33R+v7vzYNA2oZug7br0+5X2UaGXQKBgAU40gV+yZ4tPY008CLjmvsKqrLk4LZVUyGUf9+U2y2CufyJQUtGQwWHfYWZVmJ867UO6SuVS8zAKi/6hpVYKcbbhWqh/LgHDTRS7y1sCv4Tg6W544T1cNByCycBNQkqLXOU/u8w/s6p2x2MJzZjwpylxDm8YazJCkJdLDdxbZVlAoGAO2x1c0JKnu2vB6c0qa57YP/TWcmrMumKU8vjnhVAY4+dSv2VDsRaXqEMtXef4FbFqgOI62NVWGDmkoh2SSCBTYV9oP4XBpcW8wCRnQYBfEigJ5nVi4etf8ZQnyInZXUZEqCc1mJYFjtGLW4xSQCm4Afr0QISe+ldKDoqjkE3URECgYBZchQGPb8PY/GMnYp9uM+osyhX8y02dXjRMFc01JwxUGWhp/WzRsDfjv2YSLm/ZfWkV3piLhEXPU6U8zp8Kp7butH1e8atjs9Vw2LqDYMHWFfBpIvLg1zvRNvS5smpkBIlhxupWUumLfgaSNGbYCbLpZ6z8qNgOrK3LV9kfHuBzg==\n";


                 //生产地址
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private PayOrderHistoryMapper payOrderHistoryMapper;
    @Autowired
    private ReductionActivityMapper reductionActivityMapper;

    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private QuJiaPayV2Controller quJiaPayV2Controller;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private TradePaymentRecordsService tradePaymentRecordsService;
    @Autowired
    private SXFChannel sxfChannel;
    @Autowired
    private PosMachineMapper posMachineMapper;
    @Autowired
    private ClassSettlementService classSettlementService;
    private String publicKey;

    @Value("${spring.profiles.active}")
    public void setProfile(String profile){
        if (StringUtils.contains(profile,"prod")) {
            publicKey = SXFPaySign.sxfPublic;
        }else{
            publicKey = SXFPaySign.sxfTestPublic;
        }
    }


    @Override
    @Async
    public String launchLedger(Map<String, Object> request) {
        try {
            Date today = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = formatter.format(today);
         String URL  =  tianqueURLVal + "/query/ledger/launchLedger";
            String mno   = (String) request.get("mno");
            String uuid   = (String) request.get("uuid");
            String ordNo = (String) request.get("ordNo");
            PayOrder payOrderInfo =    payOrderMapper.selectOrderInfoByOrdNo(ordNo);
//        获取商户号，然后获取百分比，计算金额，然后处理
            List<DivideAccountsSettingDto> divideAccList =   payOrderMapper.selectDivideSettingDetail(mno,payOrderInfo.getStationId().toString());
//        处理分账
       if(divideAccList.size()>0 && divideAccList.get(0).getBeginMmo()!=null){
           BigDecimal amt = BigDecimal.ZERO;
           if (request.containsKey("tranType")&&request.get("tranType").equals("0001")) {
               // 非银行卡交易不处理
               BigDecimal tranAmt =   request.get("tranAmt")!=null? new BigDecimal((String)request.get("tranAmt")):BigDecimal.ZERO;
               BigDecimal feeAmt =    request.get("feeAmt")!=null? new BigDecimal((String)request.get("feeAmt")):BigDecimal.ZERO;
               amt = tranAmt.subtract(feeAmt);
           }else if(request.containsKey("tradeType")&&request.get("tradeType").equals("01")){
               BigDecimal settleAmt;
               if(request.get("settleAmt")!=null){
                    settleAmt =    request.get("settleAmt")!=null? new BigDecimal((String)request.get("settleAmt")):BigDecimal.ZERO;

               }else{
                   settleAmt =    request.get("amt")!=null? new BigDecimal((String)request.get("amt")):BigDecimal.ZERO;

               }
               BigDecimal recFeeAmt =    request.get("recFeeAmt")!=null? new BigDecimal((String)request.get("recFeeAmt")):BigDecimal.ZERO;
               amt    = settleAmt.subtract(recFeeAmt);

           }
           if (amt.compareTo(BigDecimal.ZERO) > 0) {
               JSONObject reqData = new JSONObject();              //将业务参数存放在 JSON 对象中
               reqData.put("ordNo", ordNo);       //订单号
               reqData.put("uuid", uuid);           //订单总金额
               reqData.put("mno", mno);
               reqData.put("ledgerAccountFlag", "01");

               List<Map<String, Object>> mapList  = new ArrayList<>();
               for(DivideAccountsSettingDto divideAcc :divideAccList){
                   Map<String, Object> objectMap = new HashMap<>();
                   objectMap.put("allotValue",amt.multiply(divideAcc.getPercentage()).divide(BigDecimal.valueOf(100)).setScale(2,  RoundingMode.DOWN));
                   objectMap.put("mno",divideAcc.getMmo());
                   TransactionDTO transactionDTO  = new TransactionDTO();
                   transactionDTO.setAllocatedAmount(amt);
                   transactionDTO.setAmount(amt.multiply(divideAcc.getPercentage()).divide(BigDecimal.valueOf(100)).setScale(2, RoundingMode.DOWN));
                   transactionDTO.setMmo(divideAcc.getMmo());
                   transactionDTO.setUuid(uuid);
                   transactionDTO.setBeginMmo(mno);
                   transactionDTO.setMaxPercentage(divideAcc.getMaxPercentage());
                   transactionDTO.setCreateTime(formattedDate);
                   transactionDTO.setEnterpriseId(payOrderInfo.getEnterpriseId());
                   transactionDTO.setEnterpriseName(payOrderInfo.getEnterpriseName());
                   transactionDTO.setOrderNo(ordNo);
                   transactionDTO.setDivideTxt(divideAcc.getDivideTxt());
                   transactionDTO.setMmoName(divideAcc.getMmoName());
                   transactionDTO.setPercentage(divideAcc.getPercentage());
                   if(payOrderInfo.getCommission()!=null){
                       BigDecimal commissionBigDecimal = new BigDecimal(Double.toString(payOrderInfo.getCommission()));
                       transactionDTO.setCommission(commissionBigDecimal);
                   }
                   transactionDTO.setStationId(payOrderInfo.getStationId());
                   transactionDTO.setStationName(payOrderInfo.getStationName());
                   transactionDTO.setStatus(0);
                   payOrderMapper.insertTransaction(transactionDTO);
                   mapList.add(objectMap);
               }
               reqData.put("ledgerRule",mapList);

               String req = this.getSXFPay(reqData);
               //此处不要改变reqData里面值的顺序用LinkedHashMap
               HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
               //组装加密串
               String signContent = RSASignature.getOrderContent(reqMap);
               //sign

               String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, tradeReversePayPrivatekey));
               reqMap.put("sign", sign);
               String reqStr = JSON.toJSONString(reqMap);
               log.info("sxfGoPay-随行付请求参数-" + reqStr);
               //调用第三方接口地址
               String resultJson = HttpUtils.connectPostUrl(URL, reqStr);

               log.info("sxfGoPay-随行付返回参数-" + resultJson);
// 解析resultJson
               JSONObject responseJson = JSONObject.parseObject(resultJson);
               String code = responseJson.getString("code");
               String msg = responseJson.getString("msg");

// 判断code是否等于"0000"
               if ("0000".equals(code)) {
                   Date over = new Date();
                   SimpleDateFormat overformatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                   String formattedOverDate = overformatter.format(over);
                   String ledgerFee = responseJson.getJSONObject("respData").getString("ledgerFee");
                   BigDecimal recFeeAmt = new BigDecimal(ledgerFee);
                   TransactionDTO transactionStu = new TransactionDTO();
                   transactionStu.setUuid(uuid);
                   transactionStu.setOverTime(formattedOverDate);
                   transactionStu.setRecFeeAmt(recFeeAmt);
                   transactionStu.setStatus(1);
                   payOrderMapper.updateTransactionStatus(transactionStu);
               } else if (msg.contains("原交易订单不支持分账")) {
                   // 如果msg中包含"原交易订单不支持分账"，执行这里的代码
                   TransactionDTO transactionStu = new TransactionDTO();
                   transactionStu.setUuid(uuid);
                   transactionStu.setStatus(1);
                   payOrderMapper.deleteTransactionStatus(transactionStu);
               }else{
                   Date over = new Date();
                   SimpleDateFormat overformatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                   String formattedOverDate = overformatter.format(over);
                   TransactionDTO transactionStu = new TransactionDTO();
                   transactionStu.setUuid(uuid);
                   transactionStu.setOverTime(formattedOverDate);
                   transactionStu.setStatus(2);
                   payOrderMapper.updateTransactionStatus(transactionStu);
               }
           }


       }




        }catch (Exception e){
            e.printStackTrace();
        }

        return "成功";
    }

    public static String getSXFPay(JSONObject reqData ) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        long timestamp = System.currentTimeMillis();
        String timestampStr = String.valueOf(timestamp);
        ApiRequestBean<JSONObject> reqBean = new ApiRequestBean<JSONObject>();
//        reqBean.setOrgId("57308998");//测试 合作机构id
//        reqBean.setOrgId("73153713");//生产合作机构id
        reqBean.setOrgId("92346959");//生产合作机构id
        reqBean.setReqId(UUID.randomUUID().toString().replaceAll("-", ""));//请求id 订单号
        reqBean.setSignType("RSA");//签名类型
        reqBean.setTimestamp(timestampStr);//请求时间
        reqBean.setVersion("1.0");//版本
        //将业务参数存放在 JSON 对象中
        reqBean.setReqData(reqData);
        String req = JSONObject.toJSONString(reqBean);
        return req;

    }


    @Override
    public String unifiedCallback(Map<String, Object> request) {
        log.info("=====随行付统一回调，入参：{}",request);
        String sign = (String) request.remove("sign");
        String signContent = RSASignature.getOrderContent(request);
        if (!RSASignature.doCheck(signContent, sign, this.publicKey)) {
            log.info("=====随行付回调验签失败--参数:{}",request);
            return "{\"code\":\"false\",\"msg\":\"失败\"}";
        }
        if (!request.containsKey("tranType")) {
            // 非银行卡交易
            qrTransCallback(request);
            // 非银行卡交易不处理
//回调以后用这个方法来分账
            this.launchLedger(request);
            return SUCCESS_RETURN_VALUE;
        }else{
            this.launchLedger(request);
        }
        bankCardCallback(request);
        return SUCCESS_RETURN_VALUE;
    }

    private void qrTransCallback(Map<String, Object> request){
        if (!request.containsKey("origOrdNo")) {
            // 没有origOrdNo字段，表示非退款回调，不处理
            return;
        }
//        if(!request.containsKey("realRefundAmount")){
//            // 退款会通知两条消息，第一次包含realRefundAmount字段，第二次不包含，只处理一次
//            return;
//        }
        String origOrdNo = (String) request.get("origOrdNo");
        String payWay = (String) request.get("payWay");
        if (!StringUtils.equals(payWay, "05")) {
            return;
        }
        if (StringUtils.isBlank(origOrdNo)) {
            return;
        }
        boolean his = false;
        PayOrder payOrder = payOrderMapper.selectByOrdNo(origOrdNo);
        if (payOrder == null) {
            payOrder = payOrderHistoryMapper.selectByOrdNo(origOrdNo);
            his = true;
        }
        if (payOrder == null) {
            log.info("=====码交易退款统一回调-订单不存在更新失败，订单号：{}",origOrdNo);
            return;
        }
        if (!StringUtils.equals("1",payOrder.getStatus())) {
            log.info("=====码交易退款统一回调-订单状态不对更新失败，订单号：{},status:{}",origOrdNo,payOrder.getStatus());
            return;
        }
        PayOrder update = new PayOrder();
        update.setOrderId(payOrder.getOrderId());
        update.setStatus("3");
        String payTimeStr = (String) request.get("payTime");
        if (StringUtils.isNotBlank(payTimeStr)) {
            try {
                update.setRefundSuccessDate(new SimpleDateFormat("yyyyMMddHHmmss").parse(payTimeStr));
            } catch (ParseException e) {
                log.error("时间解析失败");
                log.error(e.getMessage(), e);
            }
        }else{
            update.setRefundSuccessDate(new Date());
        }
        if (his) {
            payOrderHistoryMapper.updateByPrimaryKeySelective(update);
        }else{
            payOrderMapper.updateByPrimaryKeySelective(update);
        }
    }

    private void bankCardCallback(Map<String, Object> request){
        String tranType = (String) request.get("tranType");
//        String ordNo = (String) request.get("ordNo");
//        if (StringUtils.isBlank(ordNo)) {
//            this.savePayOrder(request);
//        }
        if (StringUtils.equals("0001",tranType)) {
            // 消费
            consumeCallback(request);
        }else if(StringUtils.equalsAny(tranType,"0002","0008")){
            // 退款
            refundCallback(request);
        }else if(StringUtils.equals("0007",tranType)){
            // 冲正
            reversalCallback(request);
        }else{
            // 其它
            log.info("=====uuid:[{}],ordNo:[{}],交易类型[{}]不处理",request.get("uuid"),request.get("ordNo"),tranType);
        }
    }

    /**
     * 刷卡成功回调
     */
    private void consumeCallback(Map<String, Object> request){
        String ordNo = (String) request.get("ordNo");
        if (StringUtils.isBlank(ordNo)) {
            SxfCallbackService bean = SpringUtils.getBean(SxfCallbackService.class);
            bean.consumeCallbackWithoutOrdNo(request);
            return;
        }
        TradePaymentRecordsDO recordsDO = new TradePaymentRecordsDO();
        recordsDO.setOrderSn(ordNo);
        recordsDO.setOrdNo((String) request.get("tranSeqNo"));
        recordsDO.setUuid((String) request.get("uuid"));
        recordsDO.setAmt(new BigDecimal((String) request.get("tranAmt")));
        recordsDO.setSubject("银行卡支付");
        recordsDO.setStatus(1);
        recordsDO.setAddTime(new Date());
        tradePaymentRecordsService.save(recordsDO);
        String tranSts = (String) request.get("tranSts");
        PayOrder payOrder = payOrderMapper.selectByOrdNo(ordNo);
        if (payOrder == null) {
            log.info("=====消费统一回调-订单不存在更新失败，订单号：{}",ordNo);
            return;
        }
        if (!StringUtils.equals("0",payOrder.getStatus())) {
            log.info("=====消费统一回调-订单状态不对，订单号：{}",ordNo);
            return;
        }
        if (StringUtils.equals("F",tranSts)) {
            // 交易失败
            if(payOrder.getActivityId()!=null) {
                //退款的时候恢复预算
                reductionActivityMapper.updateReductionActivityBudget(BigDecimal.valueOf(payOrder.getDiscountAmt()), Math.toIntExact(payOrder.getActivityId()));
            }
            log.info("=====交易状态不对,ordNo:[{}],tranSts:[{}],参数:[{}]",ordNo,tranSts,request);
            return;
        }
        if (!StringUtils.equals("S",tranSts)) {
            log.info("=====交易状态不对,ordNo:[{}],tranSts:[{}],参数:[{}]",ordNo,tranSts,request);
            return;
        }
        String payTimeStr = (String) request.get("tranDt") + request.get("tranTm");
        String amt = (String) request.get("tranAmt");
        if (StringUtils.isNotBlank(payOrder.getCustomerPhone())) {
            log.info("=====消费统一回调-银行卡加积分,orderNo:[{}]",payOrder.getOrderNo());
            transactionTemplate.executeWithoutResult(transactionStatus -> quJiaPayV2Controller.sxfPayOrderCallback(payTimeStr, ordNo, amt, null, amt, StringUtils.EMPTY, PayTypeEnum.yhk.getType()));
            return;
        }
        PayOrder updatePayOrder = new PayOrder();
        updatePayOrder.setOrderId(payOrder.getOrderId());
        updatePayOrder.setStatus("1");
        Station station = enterpriseService.selectStationById(payOrder.getStationId());
        if (StringUtils.equals("0",payOrder.getChannelFeePayer())) {
            // 司机承担渠道费
            if (station != null && station.getIsShowSaasAmtCommission() == 0) {
                // 后台订单列表不展示渠道费
                BigDecimal recAmt = payOrder.getReceivableAmt() == null ? BigDecimal.ZERO : BigDecimal.valueOf(payOrder.getReceivableAmt());
                BigDecimal disAmt = payOrder.getDiscountAmt() == null ? BigDecimal.ZERO : BigDecimal.valueOf(payOrder.getDiscountAmt());
                BigDecimal couAmt = payOrder.getDiscountCouponAmt() == null ? BigDecimal.ZERO : BigDecimal.valueOf(payOrder.getDiscountCouponAmt());
                BigDecimal amtBig = recAmt.subtract(disAmt).subtract(couAmt);
                if (amtBig.compareTo(BigDecimal.ZERO)<=0) {
                	amtBig = DecimalConstant.O_01;
                }
                updatePayOrder.setAmt(amtBig.doubleValue());
            }
        }
        if (StringUtils.isNotBlank(payTimeStr)) {
            try {
                updatePayOrder.setPayDate(new SimpleDateFormat("yyyyMMddHHmmss").parse(payTimeStr));
            } catch (ParseException e) {
                log.error("时间解析失败");
                log.error(e.getMessage(), e);
            }
        }else{
            updatePayOrder.setPayDate(new Date());
        }
        payOrderMapper.updateByPrimaryKeySelective(updatePayOrder);
        log.info("消费-订单更新成功,ordNo:[{}],payTime:[{}]",ordNo,payTimeStr);
    }

    /**
     * 没有订单号的消费回调
     * @param request
     */
    @Override
    @Async
    public void consumeCallbackWithoutOrdNo(Map<String, Object> request){
        log.info("=====订单号为空,插入订单,uuid:[{}]",request.get("uuid"));
        SxfBankCardCallbackDTO callbackDTO = null;
        try {
            callbackDTO = JsonUtils.mapToObject(request, SxfBankCardCallbackDTO.class);
        } catch (IOException e) {
            log.error("json转换失败");
            log.error(e.getMessage(), e);
        }
        if (callbackDTO == null) {
            return;
        }
        if (StringUtils.isNotBlank(callbackDTO.getOrdNo()) || !StringUtils.equals("S",callbackDTO.getTranSts())) {
            log.info("交易状态不对，不处理,uuid:[{}],ordNo:[{}],sts:[{}]",callbackDTO.getUuid(),callbackDTO.getOrdNo(),callbackDTO.getTranSts());
            return;
        }
        String payTimeStr = callbackDTO.getTranDt() + callbackDTO.getTranTm();
        Date payDate = new Date();
        if (StringUtils.isNotBlank(payTimeStr)) {
            try {
                payDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(payTimeStr);
            } catch (ParseException e) {
                log.error("时间解析失败");
                log.error(e.getMessage(), e);
            }
        }
        BigDecimal amt = new BigDecimal(callbackDTO.getTranAmt());
        String orderNo = com.platform.qujia.utils.StringUtils.generateOrdNo();
        TradePaymentRecordsDO recordsDO = new TradePaymentRecordsDO();
        recordsDO.setOrderSn(orderNo);
        recordsDO.setOrdNo(callbackDTO.getTranSeqNo());
        recordsDO.setUuid(callbackDTO.getUuid());
        recordsDO.setAmt(amt);
        recordsDO.setSubject("银行卡支付");
        recordsDO.setStatus(1);
        recordsDO.setAddTime(new Date());
        tradePaymentRecordsService.save(recordsDO);
        PayOrder payOrder = new PayOrder();
        double doubAmt = amt.doubleValue();
        payOrder.setOrderNo(orderNo);
        payOrder.setAmt(doubAmt);
        payOrder.setReceivableAmt(doubAmt);
//        payOrder.setStationId(0);
//        payOrder.setStationName(null);
//        payOrder.setEnterpriseId(0);
//        payOrder.setEnterpriseName(null);
        payOrder.setStatus("1");
        payOrder.setCreatedDate(payDate);
        payOrder.setPayDate(payDate);
        payOrder.setPayType(PayTypeEnum.yhk.getType());
        payOrder.setServiceCharge(new BigDecimal(callbackDTO.getMecFeeRate()).multiply(BigDecimal.TEN));
        payOrder.setCommission(new BigDecimal(callbackDTO.getFeeAmt()).doubleValue());
        payOrder.setChannelFeePayer("1");
        payOrder.setUtmSource("9");
        payOrderMapper.insertSelectiveOrder(payOrder);
        String trmNo = callbackDTO.getTrmNo();
        SxfQueryTerminalReq req = new SxfQueryTerminalReq();
        req.setMno(callbackDTO.getMno());
        req.setDeviceNo(trmNo);
        SxfQueryTerminalListDTO terminalListDTO = sxfChannel.queryThirdPartyTerminal(req);
        if (terminalListDTO == null
                || !StringUtils.equals(SXFChannel.BIZ_CODE_SUCCESS,terminalListDTO.getBizCode())
                || terminalListDTO.getTerminalList() == null) {
            log.info("获取终端列表失败,uuid:[{}]",callbackDTO.getUuid());
            return;
        }
        Optional<SxfTerminalDTO> first = terminalListDTO.getTerminalList().stream().filter(t -> StringUtils.equals(t.getYlTrmNo(), trmNo)).findFirst();
        if (!first.isPresent()) {
            log.info("终端号未找到,uuid:[{}],终端号:[{}]",callbackDTO.getUuid(),trmNo);
            return;
        }
        String serialNo = first.get().getSerialNo();
        StationDeviceManager form = new StationDeviceManager();
        form.setDeviceNo(serialNo);
        List<StationDeviceManager> stationDeviceManagerList = posMachineMapper.getStationDeviceManagerList(form);
        if (stationDeviceManagerList.isEmpty()) {
            log.info("设备未找到,uuid:[{}],deviceNo:[{}]",callbackDTO.getUuid(),serialNo);
            return;
        }
        StationDeviceManager deviceManager = stationDeviceManagerList.get(0);
        Integer stationId = deviceManager.getStationId();
        Station station = enterpriseService.selectStationById(stationId);
        if (station == null) {
            log.info("油站未找到,uuid:[{}],deviceNo:[{}],stationId:[{}]",callbackDTO.getUuid(),serialNo,stationId);
            return;
        }
        PayOrder update = new PayOrder();
        update.setOrderId(payOrder.getOrderId());
        update.setStationId(station.getStationId());
        update.setStationName(station.getStationName());
        update.setEnterpriseId(station.getEnterpriseId());
        update.setEnterpriseName(station.getEnterprise().getEnterpriseName());
        payOrderMapper.updateByPrimaryKeySelective(update);
    }

    /**
     * 退款回调
     */
    private void refundCallback(Map<String, Object> request){
//        String ordNo = (String) request.get("ordNo");
//        if (StringUtils.isBlank(ordNo)) {
//            ordNo = getPayOrderNo((String) request.get("ouuid"));
//        }
        String ordNo = getPayOrderNo((String) request.get("ouuid"));
        if (StringUtils.isBlank(ordNo)) {
            log.info("=====订单号为空,uuid:[{}]",request.get("uuid"));
            return;
        }
        String tranSts = (String) request.get("tranSts");
        if (!StringUtils.equals("S",tranSts)) {
            log.info("=====交易状态不对,ordNo:[{}],tranSts:[{}],参数:[{}]",ordNo,tranSts,request);
            return;
        }
        boolean his = false;
        PayOrder payOrder = payOrderMapper.selectByOrdNo(ordNo);
        if (payOrder == null) {
            payOrder = payOrderHistoryMapper.selectByOrdNo(ordNo);
            his = true;
        }
        if (payOrder == null) {
            log.info("=====退款统一回调-订单不存在更新失败，订单号：{}",ordNo);
            return;
        }
        if (!StringUtils.equals("1",payOrder.getStatus())) {
            log.info("=====退款统一回调-订单状态不对，订单号：{}",ordNo);
            return;
        }
        if(payOrder.getActivityId()!=null) {
            //退款的时候恢复预算
            reductionActivityMapper.updateReductionActivityBudget(BigDecimal.valueOf(payOrder.getDiscountAmt()), Math.toIntExact(payOrder.getActivityId()));
        }
        PayOrder updatePayOrder = new PayOrder();
        updatePayOrder.setOrderId(payOrder.getOrderId());
        updatePayOrder.setStatus("3");
        String payTimeStr = (String) request.get("tranDt") + request.get("tranTm");
        if (StringUtils.isNotBlank(payTimeStr)) {
            try {
                updatePayOrder.setRefundSuccessDate(new SimpleDateFormat("yyyyMMddHHmmss").parse(payTimeStr));
            } catch (ParseException e) {
                log.error("时间解析失败");
                log.error(e.getMessage(), e);
            }
        }else{
            updatePayOrder.setRefundSuccessDate (new Date());
        }
//        String payTimeStr = (String) request.get("tranDt") + request.get("tranTm");
//        try {
//            updatePayOrder.setPayDate(new SimpleDateFormat("yyyyMMddHHmmss").parse(payTimeStr));
//        } catch (ParseException e) {
//            log.error("时间解析失败");
//            log.error(e.getMessage(), e);
//        }
        if (his) {
            payOrderHistoryMapper.updateByPrimaryKeySelective(updatePayOrder);
        }else{
            payOrderMapper.updateByPrimaryKeySelective(updatePayOrder);
        }
        log.info("退款-订单更新成功,ordNo:[{}],payTime:[{}]",ordNo,payTimeStr);
    }

    /**
     * 冲正回调
     * @param request
     */
    private void reversalCallback(Map<String,Object> request){
//        String ordNo = (String) request.get("ordNo");
//        if (StringUtils.isBlank(ordNo)) {
//            ordNo = getPayOrderNo((String) request.get("ouuid"));
//        }
        String ordNo = getPayOrderNo((String) request.get("ouuid"));
        if (StringUtils.isBlank(ordNo)) {
            log.info("=====订单号为空,uuid:[{}]",request.get("uuid"));
            return;
        }
        String tranSts = (String) request.get("tranSts");
        if (!StringUtils.equals("S",tranSts)) {
            log.info("=====交易状态不对,ordNo:[{}],tranSts:[{}],参数:[{}]",ordNo,tranSts,request);
            return;
        }
        PayOrder payOrder = payOrderMapper.selectByOrdNo(ordNo);
        if (payOrder == null) {
            log.info("=====冲正统一回调-订单不存在更新失败，订单号：{}",ordNo);
            return;
        }
        if (!StringUtils.equals("1",payOrder.getStatus())) {
            log.info("=====冲正统一回调-订单状态不对，订单号：{}",ordNo);
            return;
        }
        if(payOrder.getActivityId()!=null) {
            //冲正的时候恢复预算
            reductionActivityMapper.updateReductionActivityBudget(BigDecimal.valueOf(payOrder.getDiscountAmt()), Math.toIntExact(payOrder.getActivityId()));
        }
        PayOrder updatePayOrder = new PayOrder();
        updatePayOrder.setOrderId(payOrder.getOrderId());
        updatePayOrder.setStatus("4");
        String payTimeStr = (String) request.get("tranDt") + request.get("tranTm");
//        if (StringUtils.isNotBlank(payTimeStr)) {
//            try {
//                updatePayOrder.setRefundSuccessDate(new SimpleDateFormat("yyyyMMddHHmmss").parse(payTimeStr));
//            } catch (ParseException e) {
//                log.error("时间解析失败");
//                log.error(e.getMessage(), e);
//            }
//        }else{
//            updatePayOrder.setRefundSuccessDate (new Date());
//        }
        payOrderMapper.updateByPrimaryKeySelective(updatePayOrder);
        log.info("冲正-订单更新成功,ordNo:[{}],payTime:[{}]",ordNo,payTimeStr);
        changeClassSettlementStatus(payOrder);
    }

    private void changeClassSettlementStatus(PayOrder payOrder){
        if (payOrder.getPayDate() == null || payOrder.getStationId() == null) {
            return;
        }
        List<String> classNos = classSettlementService.queryClassNoByPayDate(payOrder.getStationId(),payOrder.getPayDate());
        if (CollectionUtils.isEmpty(classNos) || StringUtils.isBlank(classNos.get(0))) {
            return;
        }
        log.info("冲正-更改班结状态,orderNo:[{}],classNo:[{}]",payOrder.getOrderNo(),classNos.get(0));
        classSettlementService.updateClassSettlementStatus(classNos.get(0));
    }

    private String getPayOrderNo(String ouuid){
        List<TradePaymentRecordsDO> list = tradePaymentRecordsService.list(Collections.singletonMap("ordNo",ouuid));
        if (!list.isEmpty()) {
            return list.get(0).getOrderSn();
        }
        return null;
    }

}
